package com.ntlg.sendmessage.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ntlg.sendmessage.mapper.SendSmsMapper;
import com.ntlg.sendmessage.pojo.Phone;
import com.ntlg.sendmessage.service.SendSmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;


@Service
public class SendSmsServiceImpl implements SendSmsService {
    @Autowired
    SendSmsMapper sendSmsMapper;

    @Override
    public String SendSms(String PhoneNumbers,String SignName, String TemplateCode) {
        //连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tAm7ti99pL2GnjBzq17", "lZRu9pJRE9zECBI31zdmNw6QcxJwdL");

        IAcsClient client = new DefaultAcsClient(profile);

        //构建请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");//不要修改
        request.setVersion("2017-05-25");//不要修改
        request.setAction("SendSms");
        request.putQueryParameter("PhoneNumbers", PhoneNumbers);//替要发送到的手机号码
        request.putQueryParameter("SignName", SignName);//短信签名
        request.putQueryParameter("TemplateCode", TemplateCode);//短信模板号
        //构建一个短信验证码
        HashMap<String, Object> map = new HashMap<String, Object>();
        int phoneCode = (int)((Math.random()*9+1)*100000);
        map.put("code",phoneCode);

        /*生成验证码放入数据库中*/
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        sendSmsMapper.insertPhoneCode(phoneCode,format);

        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return "短信发送成功！";
        } catch (Exception e) {
            e.printStackTrace();
            return "短信发送失败！";
        }
    }

    /*根据id查询所使用的短信模板*/
    @Override
    public Phone selectPhone(String PhoneNumbers) {
        Phone phone = sendSmsMapper.selectPhone(PhoneNumbers);
      return phone;
    }

}
